package com.sxfq.loansupermarket.backsystem.core.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.config.properties.AliyunOssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class AliyunOssUtil {

    @Autowired
    AliyunOssProperties properties;


    /**
     * 向aliyun 推送单文件    MultipartFile
     * @return
     */
    public boolean pushSingleFile(MultipartFile file, String fileName) {
        OSSClient client=null;
        InputStream inputStream= null;
        try {
            inputStream = file.getInputStream();

        String keyid=properties.getAccessKeyId();
        String keysecret=properties.getAccessKeySecret();
        String url =properties.getEndPoint();
        String BucketName=properties.getBacketName();

        client=new OSSClient(url,keyid,keysecret);
        if (!(client.doesBucketExist(BucketName))){
            // 创建Bucket。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。DBF5FB6CB011EFC69CBAE89970540D5E
            client.createBucket(BucketName);  //当为空，创建一个Bucket
        }
        PutObjectResult result= client.putObject(BucketName,fileName,inputStream);
        System.out.println(result.getETag());
        } catch (IOException e) {
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
        }finally {
            if(client!=null){
                client.shutdown();
            }
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       return false;
    }

    public String getProperties(){
        return this.properties.getBacketName()+"---"+this.properties.getAccessKeyId()+"---"+this.properties.getAccessKeySecret();
    }

    public String imgUrl(){
        return this.properties.getImgUrl();
    }


}
